package nbcp.flux.listener

import nbcp.base.comm.config
import nbcp.base.enums.AlignDirectionEnum
import nbcp.base.enums.MyOqlComponentEnum
import nbcp.base.extend.*
import nbcp.flux.ClientIp
import nbcp.flux.FluxContext
import nbcp.flux.XTraceId
import nbcp.flux.token
import nbcp.http.event.HttpClientInitEvent
import nbcp.http.event.HttpClientPreEvent
import org.slf4j.LoggerFactory
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent
import org.springframework.context.ApplicationListener

/**
 * 程序的最高事件。
 */
class HttpClientPreEventListener :
    ApplicationListener<HttpClientInitEvent> {
    init {
        config.loadedComponent = config.loadedComponent or MyOqlComponentEnum.MVC.value;
    }

    override fun onApplicationEvent(event: HttpClientInitEvent) {
        var http = event.request;
        val token = FluxContext.exchange.token
        if (token.key.HasValue) {
            logger.info("初始化传递 ${token.key}: ${token.value}")
            http.addHeader(token.key, token.value)
        }


        val xTraceId = FluxContext.exchange.XTraceId
        if (xTraceId.HasValue) {
            http.addHeader("X-Trace-Id", xTraceId)
        }
        val xRealIp = FluxContext.exchange.ClientIp
        if (xRealIp.HasValue) {
            http.addHeader("X-Real-Ip", xRealIp)
        }
    }

    companion object {
        private val logger = LoggerFactory.getLogger(this::class.java.declaringClass)
    }
}